<template>
    <div>
        <table>
            <thead>
                <th>序号</th>
                <th>单选</th>
                <th>商品名</th>
                <th>价格</th>
                <th>数量</th>
                <th>操作</th>
            </thead>
            <tr v-for="(item, index) in shops" :key="item.id">
                <td>{{ item.id }}</td>
                <td> <input type="checkbox" v-model="item.selected"></td>
                <td>{{ item.name }}</td>
                <td>{{ item.price }}</td>
                <td> 
                    <button @click="decrement(index)">-</button>
                    <input type="text" v-model="item.number" @change="validateNumber(item)">
                    <button @click="increment(index)">+</button>
                </td>
                <td><button @click="removeItem(index)">删除</button></td>
            </tr>  
        </table>
        <p>
            <input type="checkbox" v-model.item.selected="allSettled" @change="all"> 全选计算一共需要支付{{als }}元 单独计算只需{{ select }}元
        </p>
    </div>
</template>
<script>



export default {
    data() {
        return {
            allSettled:false,
            shops: [
                { id: 1, name: "html", price: 55, number: 1 ,},
                { id: 2, name: "css", price: 66, number: 1 },
                { id: 3, name: "javascript", price: 77, number: 1 },
                { id: 4, name: "jq", price: 88, number: 1 },
            ],
        }
    },
    methods: {
         increment(index) {
            this.shops[index].number++
        },
        decrement(index) {
            if (this.shops[index].number > 1) {
                this.shops[index].number--
            }
        },
        removeItem(index) {
            this.shops.splice(index, 1)
        },
        validateNumber(item) {
            if (isNaN(item.number) || item.number < 1) {
                item.number = 1
            }
        },
        // 全选
        all(){
            this.shops.forEach(item => {
                item.selected = this.allSettled
            })
        }
    },
     computed:{
        als(){
            let total = 0;
            for (let item of this.shops){
                total += item.price * item.number
            }
            return total
        },
        select(){
             let total = 0;
            for (let item of this.shops){
                if(item.selected){
                   total += item.price * item.number 
                }
                
            }
            return total
        }
     }
    
}   
</script>
<style lang="scss">
        p{
            text-align:left
        }
</style>